#include "moderngamecontroller.h"
#include "snakegamemanager.h"
#include <QDebug>
#include <QKeyEvent>
#include <QApplication>
#include <QJsonArray>
#include <QJsonObject>
#include <QRandomGenerator>
#include <QShortcut>

ModernGameController::ModernGameController(QWidget *parent)
    : QWidget(parent)
    , m_clientPrediction(nullptr)
    , m_gameRenderer(nullptr)
    , m_networkManager(nullptr)
    , m_webSocketManager(nullptr)
    , m_unifiedRenderer(nullptr)
    , m_layout(new QVBoxLayout(this))
    , m_controlLayout(new QHBoxLayout())
    , m_pauseButton(new QPushButton("暂停", this))
    , m_restartButton(new QPushButton("重新开始", this))
    , m_backButton(new QPushButton("返回大厅", this))
    , m_scoreLabel(new QLabel("分数: 0", this))
    , m_fpsLabel(new QLabel("FPS: 0", this))
    , m_currentGameState("stopped")
    , m_isGameRunning(false)
    , m_isGamePaused(false)
    , m_isConnected(false)
    , m_performanceTimer(new QTimer(this))
    , m_gameLoopTimer(new QTimer(this))
    , m_threadMonitorTimer(new QTimer(this))
    , m_threadFailureCount(0)
    , m_memoryMonitorTimer(new QTimer(this))
    , m_lastMemoryCheck(0)
    , m_currentDirection(3)  // 初始向右
    , m_gameSpeed(200)       // 200ms移动一次
    , m_currentScore(0)      // 初始分数
    , m_currentRoomId("")    // 初始房间ID
    , m_currentPlayerId("")  // 初始玩家ID
    , m_threadsRunning(false) // 初始线程状态
    , m_fallbackMode(false)   // 初始降级状态
    , m_useUnifiedPipeline(true)  // 强制使用统一渲染管线
    , m_hasFirstFrame(false)      // 首帧标记
    , m_lastInputTime(0)
    , m_inputSequence(1)
    , m_totalInputs(0)
    , m_successfulPredictions(0)
    , m_failedPredictions(0)
{
    // 设置基本属性
    setMinimumSize(1000, 700);
    setFocusPolicy(Qt::StrongFocus);

    // 确保能接收键盘事件
    setAttribute(Qt::WA_AcceptTouchEvents, false);
    setFocus();

    // 初始化性能数据
    m_performance.currentFPS = 0;
    m_performance.networkLatency = 0;
    m_performance.predictionAccuracy = 0.0f;
    m_performance.averageFrameTime = 0.0f;
    m_performance.droppedFrames = 0;
    m_performance.lastUpdateTime = QDateTime::currentMSecsSinceEpoch();

    // 初始化所有系统
    initializeSystems();

    // 设置系统连接
    setupConnections();

    // 设置性能监控定时器
    m_performanceTimer->setInterval(1000); // 每秒更新一次
    connect(m_performanceTimer, &QTimer::timeout, this, &ModernGameController::onPerformanceTimer);
    m_performanceTimer->start();

    // 设置游戏循环定时器（单人模式下不启动，避免冲突）
    m_gameLoopTimer->setInterval(m_gameSpeed);
    connect(m_gameLoopTimer, &QTimer::timeout, this, &ModernGameController::onGameLoop);
    // 注意：单人模式下游戏循环定时器不会启动，避免与SinglePlayerGameWidget冲突

    qDebug() << "ModernGameController: 现代化游戏控制器初始化完成";
    qDebug() << "  客户端预测: 已启用";
    qDebug() << "  高性能渲染: 已启用";
    qDebug() << "  异步网络: 准备就绪";
}

ModernGameController::~ModernGameController()
{
    stopGame();
    qDebug() << "ModernGameController: 现代化游戏控制器已销毁";
}

void ModernGameController::startGame(const GameConfig &config)
{
    qDebug() << "ModernGameController: 启动游戏";
    qDebug() << "  地图配置:";
    qDebug() << "    地图尺寸: 40x30";
    qDebug() << "    墙壁碰撞: 启用 (默认)";
    qDebug() << "    游戏模式: 单人模式";
    qDebug() << "  渲染配置:";
    qDebug() << "    目标FPS:" << config.targetFPS;
    qDebug() << "    特效:" << (config.enableEffects ? "启用" : "禁用");
    qDebug() << "    插值:" << (config.enableInterpolation ? "启用" : "禁用");
    qDebug() << "    预测:" << (config.enablePrediction ? "启用" : "禁用");

    m_config = config;
    m_isGameRunning = true;
    m_isGamePaused = false;
    m_currentGameState = "starting";

    // 配置渲染器
    GameRenderer::RenderConfig renderConfig;
    renderConfig.targetFPS = config.targetFPS;
    renderConfig.enableInterpolation = config.enableInterpolation;
    renderConfig.enableEffects = config.enableEffects;
    m_gameRenderer->setRenderConfig(renderConfig);

    // 启动客户端预测
    if (config.enablePrediction) {
        // 设置地图配置（与服务端保持一致）
        m_clientPrediction->setMapConfig(40, 30, true); // 40x30地图，启用墙壁碰撞
        m_clientPrediction->startPrediction();
    }

    // 使用统一渲染器，消除双重渲染系统冲突
    qDebug() << "  使用统一渲染器，启动优化的多线程渲染系统";

    // 配置统一渲染器（已在构造函数中创建和连接）
    if (m_unifiedRenderer) {
        UnifiedGameRenderer::RenderConfig unifiedConfig;
        unifiedConfig.targetFPS = config.targetFPS;
        unifiedConfig.enableEffects = config.enableEffects;
        unifiedConfig.enableInterpolation = config.enableInterpolation;
        unifiedConfig.enablePrediction = config.enablePrediction;
        unifiedConfig.renderSize = QSize(800, 600);

        // 启动统一渲染器
        m_unifiedRenderer->startGame(GameMode::SinglePlayer, unifiedConfig);
    } else {
        qCritical() << "  统一渲染器未创建！";
    }

    // 网络连接由专用网络线程负责，这里不再处理
    qDebug() << "ModernGameController: 网络连接由专用网络线程负责";

    // 设置焦点
    setFocus();
    grabKeyboard();

    // 多线程系统已集成到UnifiedGameRenderer中，无需单独启动
    qDebug() << "  使用UnifiedGameRenderer的集成多线程系统";

    // 检查WebSocket连接状态
    bool hasWebSocketConnection = false;
    if (m_webSocketManager) {
        // 检查SnakeGameManager的连接状态
        hasWebSocketConnection = m_webSocketManager->isConnectedToGame();
        qDebug() << "  WebSocket连接状态:" << hasWebSocketConnection;
    }

    // 如果有WebSocket连接，创建房间开始游戏
    if (hasWebSocketConnection) {
        createSinglePlayerRoom();
    } else {
        // 强制走网络路径，由 NetworkThread 负责创建房间；本地模式仅在明确离线时启用
        qWarning() << "  当前期望使用网络线程，未检测到连接，暂不启用本地模式";
    }

    m_currentGameState = "running";
    emit gameStateChanged(m_currentGameState);

    qDebug() << "  游戏配置:";
    qDebug() << "    目标FPS:" << config.targetFPS;
    qDebug() << "    客户端预测:" << (config.enablePrediction ? "启用" : "禁用");
    qDebug() << "    插值渲染:" << (config.enableInterpolation ? "启用" : "禁用");
    qDebug() << "    服务器URL:" << config.serverUrl;
}

void ModernGameController::startGame()
{
    GameConfig defaultConfig;
    startGame(defaultConfig);
}

void ModernGameController::stopGame()
{
    // 防止重复调用
    if (!m_isGameRunning && m_currentGameState == "stopped") {
        qDebug() << "ModernGameController: 游戏已经停止，跳过重复调用";
        return;
    }

    qDebug() << "ModernGameController: 停止游戏";

    m_isGameRunning = false;
    m_isGamePaused = false;
    m_currentGameState = "stopped";

    // 停止统一渲染器
    if (m_unifiedRenderer) {
        m_unifiedRenderer->stopGame();
    }

    // 停止客户端预测
    if (m_clientPrediction) {
        m_clientPrediction->stopPrediction();
    }

    // 停止游戏循环
    m_gameLoopTimer->stop();

    // 断开网络连接
    disconnectFromServer();

    // 释放键盘
    releaseKeyboard();

    emit gameStateChanged(m_currentGameState);
}

void ModernGameController::pauseGame()
{
    if (m_isGameRunning && !m_isGamePaused) {
        m_isGamePaused = true;
        m_currentGameState = "paused";

        // 暂停游戏循环
        m_gameLoopTimer->stop();

        // 暂停客户端预测
        if (m_clientPrediction) {
            m_clientPrediction->stopPrediction();
        }
        // 通知统一渲染器暂停（确保渲染与处理线程同步暂停）
        if (m_unifiedRenderer) {
            m_unifiedRenderer->pauseGame();
        }

        // 更新按钮文本
        m_pauseButton->setText("恢复");

        emit gameStateChanged(m_currentGameState);
        qDebug() << "ModernGameController: 游戏已暂停";
    }
}

void ModernGameController::resumeGame()
{
    if (m_isGameRunning && m_isGamePaused) {
        m_isGamePaused = false;
        m_currentGameState = "running";

        // 恢复游戏循环
        m_gameLoopTimer->start();

        // 恢复客户端预测
        if (m_clientPrediction && m_config.enablePrediction) {
            m_clientPrediction->startPrediction();
        }
        // 通知统一渲染器恢复
        if (m_unifiedRenderer) {
            m_unifiedRenderer->resumeGame();
        }

        // 更新按钮文本
        m_pauseButton->setText("暂停");

        emit gameStateChanged(m_currentGameState);
        qDebug() << "ModernGameController: 游戏已恢复";
    }
}

// connectToServer方法已删除，网络连接由专用网络线程负责

void ModernGameController::disconnectFromServer()
{
    qDebug() << "ModernGameController: 断开服务器连接";

    if (m_networkManager) {
        m_networkManager->disconnectFromServer();
    }
}

void ModernGameController::setWebSocketManager(SnakeGameManager *manager)
{
    m_webSocketManager = manager;
    m_isConnected = (manager != nullptr);
    qDebug() << "ModernGameController: WebSocket管理器已设置，连接状态:" << m_isConnected;

    // 连接WebSocket的游戏状态更新信号
    if (manager) {
        connect(manager, &SnakeGameManager::gameStateUpdated,
                this, &ModernGameController::onWebSocketGameStateUpdated);
        connect(manager, &SnakeGameManager::gameEnded,
                this, &ModernGameController::onPlayerDied);

        // 连接房间管理信号
        connect(manager, &SnakeGameManager::roomCreated,
                this, &ModernGameController::onRoomCreated);
        connect(manager, &SnakeGameManager::roomJoined,
                this, &ModernGameController::onRoomJoined);

        // 连接WebSocket连接状态信号
        connect(manager, &SnakeGameManager::connected,
                this, [this]() {
                    qDebug() << "ModernGameController: WebSocket已连接";
                    m_isConnected = true;
                });
        connect(manager, &SnakeGameManager::disconnected,
                this, [this](const QString &reason) {
                    qDebug() << "ModernGameController: WebSocket已断开:" << reason;
                    m_isConnected = false;
                });
        connect(manager, &SnakeGameManager::authenticated,
                this, [this](const QJsonObject &authResult) {
                    qDebug() << "ModernGameController: WebSocket已认证";
                    m_isConnected = true;
                });

        // 注意：SnakeGameManager没有单独的foodEaten信号，食物信息包含在gameStateUpdated中
    }
}

void ModernGameController::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "ModernGameController: 收到键盘事件，按键:" << event->key()
             << "游戏运行状态:" << m_isGameRunning << "暂停状态:" << m_isGamePaused;

    if (!m_isGameRunning || m_isGamePaused) {
        qDebug() << "ModernGameController: 游戏未运行或已暂停，只处理系统控制";
        // 只处理系统级别的控制
        switch (event->key()) {
            case Qt::Key_Escape:
                stopGame();
                return;
        }
        QWidget::keyPressEvent(event);
        return;
    }

    // === 方向控制键处理 ===
    int direction = -1;
    switch (event->key()) {
        case Qt::Key_W:
        case Qt::Key_Up:
            direction = 0;  // UP
            break;
        case Qt::Key_S:
        case Qt::Key_Down:
            direction = 1;  // DOWN
            break;
        case Qt::Key_A:
        case Qt::Key_Left:
            direction = 2;  // LEFT
            break;
        case Qt::Key_D:
        case Qt::Key_Right:
            direction = 3;  // RIGHT
            break;
        case Qt::Key_Space:
            // 暂停/恢复游戏
            if (m_isGamePaused) {
                resumeGame();
            } else {
                pauseGame();
            }
            event->accept();
            return;
        case Qt::Key_Escape:
            stopGame();
            event->accept();
            return;
    }

    if (direction != -1) {
        qDebug() << "ModernGameController: 处理键盘输入，方向:" << direction;
        handleUserInput(direction);
        event->accept();
    } else {
        QWidget::keyPressEvent(event);
    }
}

void ModernGameController::keyReleaseEvent(QKeyEvent *event)
{
    m_pressedKeys.remove(event->key());
    QWidget::keyReleaseEvent(event);
}

void ModernGameController::focusInEvent(QFocusEvent *event)
{
    qDebug() << "ModernGameController: 获得焦点";
    QWidget::focusInEvent(event);
    // 减少焦点抢夺，只在游戏运行时才抢夺键盘
    if (m_isGameRunning && !m_isGamePaused) {
        this->grabKeyboard();
    }
}

bool ModernGameController::eventFilter(QObject *obj, QEvent *event)
{
    // 仅当本控件可见时兜底拦截键盘，避免影响其他页面
    if (this->isVisible()) {
        if (event->type() == QEvent::KeyPress) {
            auto *ke = static_cast<QKeyEvent*>(event);
            qDebug() << "[EF] ModernGameController: 收到键盘事件，按键:" << ke->key()
                     << "当前焦点:" << (qApp->focusWidget() ? qApp->focusWidget()->metaObject()->className() : "null");
            // 复用现有按键处理逻辑
            this->keyPressEvent(ke);
            return true; // 已处理
        }
    }
    return QWidget::eventFilter(obj, event);
}

void ModernGameController::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    qApp->installEventFilter(this);
    // 强化焦点归属
    this->setFocusPolicy(Qt::StrongFocus);
    this->setFocus(Qt::ActiveWindowFocusReason);
    this->grabKeyboard();
    qDebug() << "ModernGameController: showEvent -> 安装事件过滤并抓取键盘";
}

void ModernGameController::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    qApp->removeEventFilter(this);
    qDebug() << "ModernGameController: hideEvent -> 卸载事件过滤";
}


void ModernGameController::focusOutEvent(QFocusEvent *event)
{
    qDebug() << "ModernGameController: 失去焦点";
    QWidget::focusOutEvent(event);
}

void ModernGameController::initializeSystems()
{
    qDebug() << "ModernGameController: 初始化系统";

    // 创建客户端预测系统
    m_clientPrediction = new ClientPrediction(this);

    // 创建游戏渲染器
    m_gameRenderer = new GameRenderer(this);

    // 创建网络管理器
    m_networkManager = new AsyncNetworkManager(this);

    // 创建统一渲染器（新的优化架构）
    m_unifiedRenderer = new UnifiedGameRenderer(this);

    // 旧的多线程组件已移除，功能已集成到UnifiedGameRenderer中

    // 设置控制按钮布局
    m_controlLayout->addWidget(m_scoreLabel);
    m_controlLayout->addWidget(m_fpsLabel);
    m_controlLayout->addStretch(); // 弹性空间
    m_controlLayout->addWidget(m_pauseButton);
    m_controlLayout->addWidget(m_restartButton);
    m_controlLayout->addWidget(m_backButton);

    // 设置主布局
    m_layout->setContentsMargins(5, 5, 5, 5);
    m_layout->addLayout(m_controlLayout);
    m_layout->addWidget(m_gameRenderer, 1); // 游戏区域占主要空间

    qDebug() << "  客户端预测系统: 已创建";
    qDebug() << "  游戏渲染器: 已创建";
    qDebug() << "  网络管理器: 待实现";

    // === 保底输入：QShortcut，避免焦点丢失时无法控制 ===
    auto setupShortcut = [this](int key, int dir){
        auto *sc = new QShortcut(QKeySequence(key), this);
        sc->setContext(Qt::WidgetWithChildrenShortcut);
        connect(sc, &QShortcut::activated, this, [this, dir](){
            qDebug() << "[QS] 触发方向:" << dir;
            handleUserInput(dir);
        });
    };
    setupShortcut(Qt::Key_Up, 0);
    setupShortcut(Qt::Key_Down, 1);
    setupShortcut(Qt::Key_Left, 2);
    setupShortcut(Qt::Key_Right, 3);

}

void ModernGameController::setupConnections()
{
    qDebug() << "ModernGameController: 设置系统连接";

    // 客户端预测系统连接
    connect(m_clientPrediction, &ClientPrediction::predictedStateUpdated,
            this, &ModernGameController::onPredictedStateUpdated);

    connect(m_clientPrediction, &ClientPrediction::sendInputToServer,
            this, &ModernGameController::onSendInputToServer);

    connect(m_clientPrediction, &ClientPrediction::predictionError,
            this, &ModernGameController::onPredictionError);

    connect(m_clientPrediction, &ClientPrediction::foodEaten,
            this, &ModernGameController::onFoodEaten);

    // 游戏渲染器连接（暂时禁用GameRenderer的FPS统计，使用RenderThread的）
    // connect(m_gameRenderer, &GameRenderer::frameRateUpdated,
    //         this, &ModernGameController::onFrameRateUpdated);

    // 网络管理器连接
    if (m_networkManager) {
        connect(m_networkManager, &AsyncNetworkManager::connectionStateChanged,
                this, &ModernGameController::onConnectionStateChanged);

        connect(m_networkManager, &AsyncNetworkManager::gameStateReceived,
                this, &ModernGameController::onGameStateReceived);

        connect(m_networkManager, &AsyncNetworkManager::inputAcknowledged,
                this, &ModernGameController::onInputAcknowledged);

        connect(m_networkManager, &AsyncNetworkManager::networkStatsUpdated,
                this, &ModernGameController::onNetworkStatsUpdated);
    }

    // UI按钮连接
    connect(m_pauseButton, &QPushButton::clicked, this, [this]() {
        if (m_isGamePaused) {
            resumeGame();
        } else {
            pauseGame();
        }
    });

    connect(m_restartButton, &QPushButton::clicked, this, [this]() {
        qDebug() << "ModernGameController: 重置按钮被点击";
        stopGame();

        // 等待停止完成后再重新开始
        QTimer::singleShot(500, this, [this]() {
            qDebug() << "ModernGameController: 延迟重新开始游戏";
            GameConfig config;
            startGame(config);
        });
    });

    connect(m_backButton, &QPushButton::clicked, this, [this]() {
        qDebug() << "ModernGameController: 返回大厅按钮被点击";
        stopGame();

        // 等待停止完成后再发送返回信号
        QTimer::singleShot(200, this, [this]() {
            qDebug() << "ModernGameController: 发送返回大厅信号";
            emit gameStateChanged("back_to_lobby");
        });
    });

    // 连接统一渲染器信号（确保唯一连接）
    if (m_unifiedRenderer) {
        // 先断开所有旧连接，确保不重复连接
        disconnect(m_unifiedRenderer, nullptr, this, nullptr);

        bool conn1 = connect(m_unifiedRenderer, &UnifiedGameRenderer::frameReady,
                this, &ModernGameController::onFrameReady, Qt::QueuedConnection);
        bool conn2 = connect(m_unifiedRenderer, &UnifiedGameRenderer::gameEnded,
                this, &ModernGameController::onPlayerDied, Qt::QueuedConnection);
        bool conn3 = connect(m_unifiedRenderer, &UnifiedGameRenderer::renderingError,
                this, &ModernGameController::onRenderingError, Qt::QueuedConnection);
        bool conn4 = connect(m_unifiedRenderer, &UnifiedGameRenderer::fpsChanged,
                this, [this](int fps) {
                    // 更新FPS显示
                    if (m_fpsLabel) {
                        m_fpsLabel->setText(QString("FPS: %1").arg(fps));
                    }
                    // 更新性能统计
                    m_performance.currentFPS = fps;
                }, Qt::QueuedConnection);

        // 连接渲染数据更新信号，同步更新 GameRenderer 的目标状态
        bool conn5 = connect(m_unifiedRenderer, &UnifiedGameRenderer::renderDataUpdated,
                this, &ModernGameController::onRenderDataUpdated, Qt::QueuedConnection);

        // 连接首帧就绪信号
        bool conn6 = connect(m_unifiedRenderer, &UnifiedGameRenderer::firstFrameReady,
                this, [this](qint64 duration) {
                    qDebug() << "*** 首帧就绪，耗时:" << duration << "ms ***";
                    m_hasFirstFrame = true;

                    // 验证首帧耗时指标（目标<150ms）
                    if (duration < 150) {
                        qDebug() << "✓ 首帧耗时达标:" << duration << "ms < 150ms";
                    } else {
                        qWarning() << "✗ 首帧耗时超标:" << duration << "ms >= 150ms";
                    }
                }, Qt::QueuedConnection);

        qDebug() << "  统一渲染器信号连接结果:" << conn1 << conn2 << conn3 << conn4 << conn5 << conn6;
        qDebug() << "  当前ModernGameController实例:" << this;
        qDebug() << "  UnifiedGameRenderer实例:" << m_unifiedRenderer;

        // 验证连接数量
        int receiverCount = QObject::receivers(SIGNAL(frameReady(QPixmap)));
        qDebug() << "  frameReady信号接收者数量:" << receiverCount;
    }

    // 设置线程监控定时器
    m_threadMonitorTimer->setInterval(5000); // 每5秒检查一次
    connect(m_threadMonitorTimer, &QTimer::timeout, this, &ModernGameController::monitorThreadHealth);

    // 设置内存监控定时器
    m_memoryMonitorTimer->setInterval(10000); // 每10秒检查一次
    connect(m_memoryMonitorTimer, &QTimer::timeout, this, &ModernGameController::monitorMemoryUsage);
    m_memoryMonitorTimer->start();

    qDebug() << "  系统连接设置完成";
}

void ModernGameController::initializeGameData()
{
    qDebug() << "ModernGameController: 初始化游戏数据（等待服务器模式）";

    // 不创建测试蛇数据，直接初始化为空状态
    // 等待服务器发送真实的游戏数据

    // 清空食物数据
    m_currentFoods.clear();

    // 创建空的初始预测状态
    ClientPrediction::PredictedState initialState;
    initialState.snakeBody.clear(); // 空蛇身
    initialState.direction = 3; // 向右
    initialState.score = 0;
    initialState.timestamp = QDateTime::currentMSecsSinceEpoch();
    initialState.isValid = false; // 标记为无效，等待服务器数据

    // 发送空状态到客户端预测系统
    if (m_clientPrediction) {
        m_clientPrediction->setCurrentFoods(m_currentFoods);
        // 不发送初始蛇状态，等待服务器数据
    }

    // 发送空状态到渲染器，显示等待界面
    if (m_gameRenderer) {
        qDebug() << "  设置渲染器为等待状态 - 无蛇身，无食物";
        m_gameRenderer->setServerState(QList<QPoint>(), m_currentFoods);
        // 不设置预测状态，让渲染器显示等待界面
        qDebug() << "  渲染器等待状态已设置";
    } else {
        qDebug() << "  错误：渲染器为空！";
    }

    qDebug() << "  等待服务器数据...";
    qDebug() << "  初始状态：无蛇身，无食物，等待连接";
}

void ModernGameController::createSinglePlayerRoom()
{
    qDebug() << "ModernGameController: 创建单人游戏房间";

    if (!m_webSocketManager) {
        qWarning() << "  WebSocket管理器为空，无法创建房间";
        return;
    }

    // 根据API文档构建房间配置
    QJsonObject roomConfig;
    roomConfig["max_players"] = 1;           // 单人模式
    roomConfig["game_mode"] = "classic";     // 经典模式
    roomConfig["private"] = false;           // 公开房间
    roomConfig["room_name"] = "单人游戏房间";
    roomConfig["map_width"] = 40;            // 地图宽度
    roomConfig["map_height"] = 30;           // 地图高度
    roomConfig["game_speed_ms"] = 200;       // 游戏速度
    roomConfig["enable_walls"] = true;       // 启用墙壁
    roomConfig["enable_special_foods"] = true; // 启用特殊食物

    // 发送创建房间消息
    QJsonObject createRoomMsg;
    createRoomMsg["type"] = "create_room";
    createRoomMsg["room_config"] = roomConfig;

    // 使用WebSocket发送消息
    if (m_webSocketManager->sendMessage(createRoomMsg)) {
        qDebug() << "  房间创建请求已发送";
    } else {
        qWarning() << "  房间创建请求发送失败";
    }
}

void ModernGameController::generateNewFood(const QPoint &eatenFoodPos)
{
    // 移除被吃掉的食物
    m_currentFoods.removeAll(eatenFoodPos);

    // 生成新食物位置（避免与蛇身重叠）
    QPoint newFood;
    bool validPosition = false;
    int attempts = 0;

    while (!validPosition && attempts < 100) {
        newFood.setX(QRandomGenerator::global()->bounded(40));
        newFood.setY(QRandomGenerator::global()->bounded(30));

        // 检查是否与现有食物重叠
        validPosition = !m_currentFoods.contains(newFood);

        // TODO: 检查是否与蛇身重叠（需要获取当前蛇身位置）

        attempts++;
    }

    if (validPosition) {
        m_currentFoods.append(newFood);
        qDebug() << "ModernGameController: 生成新食物位置:" << newFood;

        // 更新渲染器
        if (m_gameRenderer) {
            m_gameRenderer->setServerState(QList<QPoint>(), m_currentFoods); // 空蛇身，只更新食物
        }

        // 更新客户端预测的食物位置
        if (m_clientPrediction) {
            m_clientPrediction->setCurrentFoods(m_currentFoods);
        }
    }
}

void ModernGameController::handleUserInput(int direction)
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 timeSinceLastInput = currentTime - m_lastInputTime;

    // 优化：只在方向真正改变时才处理和发送网络请求
    bool directionChanged = (direction != m_currentDirection);

    // 如果方向没有改变，只做本地预测，不发送网络请求
    if (!directionChanged) {
        // 防抖：相同方向的重复输入需要间隔至少50ms
        if (timeSinceLastInput < 50) {
            return;
        }

        // 只更新本地预测，不发送网络请求
        if (m_clientPrediction) {
            m_clientPrediction->handleUserInput(direction);
        }
        m_lastInputTime = currentTime;
        return;
    }

    // 方向改变时的处理
    qDebug() << "ModernGameController: 处理用户输入:" << direction << "序列号:" << m_inputSequence;
    qDebug() << "  方向变化: " << m_currentDirection << " -> " << direction;

    // 更新当前方向
    m_currentDirection = direction;

    // 记录输入时间与统计
    m_pressedKeys.insert(direction);
    m_lastInputTime = currentTime;
    m_totalInputs++;
    m_inputSequence++;

    // 安全预警：检查这个方向是否会导致死亡
    if (m_clientPrediction) {
        ClientPrediction::PredictedState currentState = m_clientPrediction->getCurrentState();
        ClientPrediction::PredictedState predictedState = m_clientPrediction->predictNextState(currentState, direction);

        if (!predictedState.isValid) {
            qWarning() << "ModernGameController: 危险方向警告！方向" << direction << "可能导致死亡";
            // 可以在这里显示UI警告或阻止输入
            // 但为了保持游戏流畅性，仍然发送输入
        }
    }

    // 立即发送到客户端预测系统（最高优先级）
    if (m_clientPrediction) {
        m_clientPrediction->handleUserInput(direction);
    }

    // 只在方向真正改变时才发送到网络线程
    emit directionChangeRequested(direction);
}

void ModernGameController::onPredictedStateUpdated(const ClientPrediction::PredictedState &predictedState)
{
    // 将预测状态发送到渲染器
    if (m_gameRenderer) {
        m_gameRenderer->setPredictedState(predictedState);
    }

    // 发送游戏事件
    QVariantMap eventData;
    eventData["snakeLength"] = predictedState.snakeBody.size();
    eventData["direction"] = predictedState.direction;
    eventData["score"] = predictedState.score;
    emit gameEvent("predicted_state_updated", eventData);
}

void ModernGameController::onSendInputToServer(int direction, int sequenceNumber)
{
    qDebug() << "ModernGameController: 客户端预测请求发送输入到服务器:" << direction
             << "序列号:" << sequenceNumber;

    // 新架构：不再在这里直接发送WebSocket消息，避免重复发送
    // 真正的发送已由 handleUserInput -> directionChangeRequested -> MainWindow -> NetworkThread 完成
    // 这里只做本地ACK以保持客户端预测系统的流畅运行

    qDebug() << "  注意：实际发送由NetworkThread处理，这里仅做预测系统ACK";

    // 记录发送时间用于延迟计算
    m_inputSendTimes[sequenceNumber] = QDateTime::currentMSecsSinceEpoch();

    // 立即确认输入（因为使用服务器权威 + NetworkThread发送）
    QTimer::singleShot(5, this, [this, sequenceNumber]() {
        onInputAcknowledged(sequenceNumber, QDateTime::currentMSecsSinceEpoch());
    });
}

void ModernGameController::onFrameRateUpdated(int fps, float frameTime)
{
    m_performance.currentFPS = fps;
    m_performance.averageFrameTime = frameTime;

    // 更新FPS标签
    m_fpsLabel->setText(QString("FPS: %1").arg(fps));

    // 检测掉帧
    if (fps < m_config.targetFPS * 0.9f) {
        m_performance.droppedFrames++;
    }
}

void ModernGameController::onPredictionError(float errorMagnitude)
{
    qDebug() << "ModernGameController: 预测错误，误差:" << errorMagnitude;

    m_failedPredictions++;

    // 如果预测错误率过高，可以调整预测参数
    float errorRate = float(m_failedPredictions) / (m_successfulPredictions + m_failedPredictions);
    if (errorRate > 0.3f) { // 30%错误率
        qDebug() << "  预测错误率过高:" << errorRate << "考虑调整参数";
    }
}

void ModernGameController::onFoodEaten(const QPoint &foodPosition)
{
    qDebug() << "ModernGameController: 客户端预测食物被吃，位置:" << foodPosition;

    // 在服务器权威模式下，不在客户端更新分数和生成食物
    // 这些将由服务器的游戏状态更新处理

    // 播放特效
    if (m_gameRenderer) {
        QPointF effectPos(foodPosition.x(), foodPosition.y());
        m_gameRenderer->playEffect("food_eaten", effectPos);
    }

    // 发送游戏事件
    QVariantMap eventData;
    eventData["foodPosition"] = foodPosition;
    emit gameEvent("food_eaten_predicted", eventData);
}

void ModernGameController::onConnectionStateChanged(bool connected)
{
    qDebug() << "ModernGameController: 连接状态变化:" << (connected ? "已连接" : "已断开");

    m_isConnected = connected;

    if (connected) {
        emit gameEvent("network_connected", QVariant());
    } else {
        emit gameEvent("network_disconnected", QVariant());
    }
}

void ModernGameController::onNetworkStatsUpdated(const AsyncNetworkManager::NetworkStats &stats)
{
    m_performance.networkLatency = stats.latency;

    // 发送网络统计事件
    QVariantMap statsData;
    statsData["latency"] = stats.latency;
    statsData["packetLoss"] = stats.packetLoss;
    statsData["bandwidth"] = stats.bandwidth;
    statsData["messagesPerSecond"] = stats.messagesPerSecond;

    emit gameEvent("network_stats", statsData);
}

void ModernGameController::onInputAcknowledged(int sequenceNumber, qint64 serverTimestamp)
{
    qDebug() << "ModernGameController: 输入确认，序列号:" << sequenceNumber;

    // 计算网络延迟
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    int latency = currentTime - serverTimestamp;

    m_performance.networkLatency = latency;
    m_latencyHistory.append(latency);

    // 限制延迟历史大小
    while (m_latencyHistory.size() > 100) {
        m_latencyHistory.removeFirst();
    }

    // 更新客户端预测的网络延迟
    if (m_clientPrediction) {
        m_clientPrediction->setNetworkLatency(latency);
    }
}

void ModernGameController::onGameStateReceived(const QJsonObject &gameState, qint64 serverTimestamp)
{
    // 解析服务器游戏状态
    ClientPrediction::PredictedState serverState = parseServerGameState(gameState);

    if (serverState.isValid) {
        // 发送到客户端预测系统进行校正
        if (m_clientPrediction) {
            m_clientPrediction->receiveServerState(
                serverState.snakeBody,
                serverState.direction,
                serverTimestamp,
                serverState.score
            );
        }

        // 发送到渲染器作为权威状态
        if (m_gameRenderer) {
            QList<QPoint> foods; // TODO: 从gameState解析食物
            m_gameRenderer->setServerState(serverState.snakeBody, foods);
        }

        m_successfulPredictions++;
    }
}

void ModernGameController::onPerformanceTimer()
{
    updatePerformanceStats();

    // 发送性能统计
    emit performanceStats(
        m_performance.currentFPS,
        m_performance.networkLatency,
        m_performance.predictionAccuracy
    );

    // 自动优化性能
    optimizePerformance();
}

void ModernGameController::onGameLoop()
{
    if (!m_isGameRunning || m_isGamePaused) {
        return;
    }

    // 移除自动移动逻辑，避免高频发送相同方向
    // 蛇的移动应该由服务器驱动，客户端只在用户实际按键时发送方向变更
    // handleUserInput(m_currentDirection); // 已移除
}

ClientPrediction::PredictedState ModernGameController::parseServerGameState(const QJsonObject &gameState)
{
    ClientPrediction::PredictedState state;
    state.isValid = false;

    // TODO: 实现JSON解析逻辑
    // 这里需要根据实际的服务器数据格式来解析

    return state;
}

void ModernGameController::updatePerformanceStats()
{
    // 计算预测准确率
    int totalPredictions = m_successfulPredictions + m_failedPredictions;
    if (totalPredictions > 0) {
        m_performance.predictionAccuracy = float(m_successfulPredictions) / totalPredictions;
    }

    qDebug() << "ModernGameController: 性能统计";
    qDebug() << "  FPS:" << m_performance.currentFPS;
    qDebug() << "  网络延迟:" << m_performance.networkLatency << "ms";
    qDebug() << "  预测准确率:" << (m_performance.predictionAccuracy * 100) << "%";
    qDebug() << "  总输入次数:" << m_totalInputs;
}

void ModernGameController::optimizePerformance()
{
    static int lowFPSCount = 0;
    static int highLatencyCount = 0;

    // FPS优化
    if (m_performance.currentFPS < m_config.targetFPS * 0.8f) {
        lowFPSCount++;
        qDebug() << "ModernGameController: FPS过低" << m_performance.currentFPS
                 << "连续次数:" << lowFPSCount;

        if (lowFPSCount >= 3) { // 连续3次FPS过低
            // 自动降低渲染质量
            GameRenderer::RenderConfig currentConfig;
            currentConfig.targetFPS = m_config.targetFPS;
            currentConfig.enableInterpolation = m_config.enableInterpolation;
            currentConfig.enableEffects = false; // 关闭特效
            currentConfig.animationSpeed = 0.8f; // 降低动画速度

            if (m_gameRenderer) {
                m_gameRenderer->setRenderConfig(currentConfig);
            }

            qDebug() << "  自动优化：关闭特效，降低动画速度";
            lowFPSCount = 0;

            emit gameEvent("performance_optimized", "effects_disabled");
        }
    } else {
        lowFPSCount = 0;
    }

    // 网络延迟优化
    if (m_performance.networkLatency > 200) {
        highLatencyCount++;
        qDebug() << "ModernGameController: 网络延迟过高" << m_performance.networkLatency
                 << "ms，连续次数:" << highLatencyCount;

        if (highLatencyCount >= 3) { // 连续3次延迟过高
            // 调整预测参数
            if (m_clientPrediction) {
                m_clientPrediction->setNetworkLatency(m_performance.networkLatency);
            }

            // 调整网络配置
            if (m_networkManager) {
                m_networkManager->setNetworkConfig(
                    true,  // 启用压缩
                    5,     // 增加重试次数
                    2000   // 增加心跳间隔
                );
            }

            qDebug() << "  自动优化：启用压缩，调整预测参数";
            highLatencyCount = 0;

            emit gameEvent("performance_optimized", "network_optimized");
        }
    } else {
        highLatencyCount = 0;
    }

    // 预测准确率优化
    if (m_performance.predictionAccuracy < 0.7f && m_totalInputs > 50) {
        qDebug() << "ModernGameController: 预测准确率过低" << m_performance.predictionAccuracy;

        // 可以考虑调整预测算法参数
        emit gameEvent("performance_warning", "low_prediction_accuracy");
    }

    // 内存优化（简化版本）
    static int optimizationCount = 0;
    if (++optimizationCount % 60 == 0) { // 每60秒优化一次
        // 清理延迟历史
        while (m_latencyHistory.size() > 50) {
            m_latencyHistory.removeFirst();
        }

        qDebug() << "ModernGameController: 执行内存优化";
    }
}

void ModernGameController::onWebSocketGameStateUpdated(const QJsonObject &gameState)
{
    qDebug() << "ModernGameController: 收到游戏状态更新（传统路径）";

    // 检查是否使用DirectDataChannel优化路径
    // 如果DirectDataChannel已经在处理，则跳过此处理
    // 这是一个兼容性处理，优先使用DirectDataChannel

    qWarning() << "  注意：此消息应该通过DirectDataChannel处理，传统路径已弃用";
    qWarning() << "  请确保DirectDataChannel已正确连接和启动";

    // 为了避免重复处理，这里不再处理游戏状态更新
    // 所有游戏状态更新应该通过DirectDataChannel → UnifiedGameRenderer路径处理
}

// 旧的startThreads和stopThreads方法已移除，多线程功能已集成到UnifiedGameRenderer中

// 旧的onRenderDataReady方法已移除，现在通过UnifiedGameRenderer的信号直接处理

void ModernGameController::onRenderDataUpdated(const RenderReadyGameData &data)
{
    // 降噪：每60帧打印一次摘要
    static int updateCount = 0;
    updateCount++;
    if (updateCount % 60 == 1) {
        qDebug() << "*** ModernGameController::onRenderDataUpdated (每60帧摘要) ***";
        qDebug() << "接收实例:" << this;
        qDebug() << "收到渲染数据更新，蛇身长度:" << data.snakeBody.size();
        qDebug() << "食物数量:" << data.foods.size();
        qDebug() << "数据有效:" << data.isValid;
        qDebug() << "GameRenderer 存在:" << (m_gameRenderer != nullptr);
        qDebug() << "使用统一管线:" << m_useUnifiedPipeline;
    }

    // 首帧标记
    if (!m_hasFirstFrame && data.isValid && !data.snakeBody.isEmpty()) {
        m_hasFirstFrame = true;
        qDebug() << "*** 首帧接收成功 - 蛇身:" << data.snakeBody.size() << "食物:" << data.foods.size() << " ***";
    }

    if (!data.isValid) {
        qWarning() << "收到无效渲染数据，跳过更新";
        return;
    }

    // 如果使用统一管线，更新GameRenderer的目标状态（用于原生渲染路径的兼容）
    if (m_useUnifiedPipeline && m_gameRenderer) {
        // 将服务器状态转换为预测状态格式
        ClientPrediction::PredictedState predictedState;
        predictedState.snakeBody = data.snakeBody;
        predictedState.direction = data.direction;
        predictedState.score = data.score;
        predictedState.isValid = data.isValid;
        predictedState.timestamp = data.timestamp;

        // 设置到GameRenderer
        m_gameRenderer->setPredictedState(predictedState);

        if (updateCount % 60 == 1) {
            qDebug() << "已更新GameRenderer目标状态，蛇身:" << predictedState.snakeBody.size();
        }

        // 强制更新显示
        m_gameRenderer->update();
    } else {
        qWarning() << "GameRenderer 不存在，无法更新目标状态";
    }
}

void ModernGameController::onFrameReady(const QPixmap &frame)
{
    // 确保在主线程中执行UI更新
    if (QThread::currentThread() != this->thread()) {
        QMetaObject::invokeMethod(this, "onFrameReady", Qt::QueuedConnection,
                                  Q_ARG(QPixmap, frame));
        return;
    }

    // 统计UI实际帧率
    qint64 now = QDateTime::currentMSecsSinceEpoch();
    if (m_uiLastFpsTime == 0) m_uiLastFpsTime = now;
    m_uiFrameCount++;
    if (now - m_uiLastFpsTime >= 1000) {
        m_uiFps.store(m_uiFrameCount, std::memory_order_relaxed);
        m_uiFrameCount = 0;
        m_uiLastFpsTime = now;
        // 更新标签（与渲染线程FPS合并显示）
        if (m_fpsLabel) {
            m_fpsLabel->setText(QString("FPS: Render %1 / UI %2")
                                .arg(m_performance.currentFPS)
                                .arg(m_uiFps.load(std::memory_order_relaxed)));
        }
    }

    // 降噪：每60帧打印一次诊断信息，避免IO阻塞导致卡顿
    static int frameLogCount = 0;
    frameLogCount++;
    if (frameLogCount % 60 == 1) {
        qDebug() << "=== 帧渲染诊断 ===";
        qDebug() << "收到帧，尺寸:" << frame.size();
        qDebug() << "帧是否为空:" << frame.isNull();
        qDebug() << "ModernGameController可见:" << isVisible();
        qDebug() << "GameRenderer存在:" << (m_gameRenderer != nullptr);
    }

    if (m_gameRenderer) {
        if (frameLogCount % 60 == 1) {
            qDebug() << "GameRenderer可见:" << m_gameRenderer->isVisible();
            qDebug() << "GameRenderer尺寸:" << m_gameRenderer->size();
            qDebug() << "GameRenderer父组件:" << m_gameRenderer->parent();
        }

        // 将渲染好的帧显示到GameRenderer上（现在安全地在主线程中）
        m_gameRenderer->setCustomFrame(frame);
        m_gameRenderer->update(); // 安全地触发重绘

        if (frameLogCount % 60 == 1) {
            qDebug() << "帧已设置到GameRenderer并触发更新";
        }
    } else {
        if (frameLogCount % 60 == 1) {
            qWarning() << "GameRenderer不存在，无法显示帧";
        }
    }
}

// 旧的性能统计方法已移除，现在使用UnifiedGameRenderer的性能统计

void ModernGameController::processFallbackGameState(const QJsonObject &gameState)
{
    qDebug() << "ModernGameController: 降级模式处理游戏状态";

    // 简化的游戏状态处理（直接更新到GameRenderer）
    QJsonObject data = gameState["data"].toObject();
    QJsonArray snakesArray = data["snakes"].toArray();
    QJsonArray foodsArray = data["foods"].toArray();

    if (!snakesArray.isEmpty()) {
        QJsonObject snakeData = snakesArray[0].toObject();
        int score = snakeData["score"].toInt();
        bool alive = snakeData["alive"].toBool();

        // 更新分数
        m_currentScore = score;
        if (m_scoreLabel) {
            m_scoreLabel->setText(QString("分数: %1").arg(score));
        }

        // 解析蛇身体
        QList<QPoint> snakeBody;
        QJsonArray bodyArray = snakeData["body"].toArray();
        for (const QJsonValue &segment : bodyArray) {
            QJsonObject pos = segment.toObject();
            if (pos.contains("x") && pos.contains("y")) {
                snakeBody.append(QPoint(pos["x"].toInt(), pos["y"].toInt()));
            }
        }

        // 解析食物
        QList<QPoint> foods;
        for (const QJsonValue &food : foodsArray) {
            QJsonObject foodObj = food.toObject();
            QJsonObject position = foodObj["position"].toObject();
            if (position.contains("x") && position.contains("y")) {
                foods.append(QPoint(position["x"].toInt(), position["y"].toInt()));
            }
        }

        // 直接更新到GameRenderer
        if (m_gameRenderer) {
            m_gameRenderer->setServerState(snakeBody, foods);
            m_gameRenderer->update();
        }

        // 检查游戏结束
        if (!alive) {
            QTimer::singleShot(100, this, &ModernGameController::onPlayerDied);
        }
    }
}

void ModernGameController::onPlayerDied()
{
    qDebug() << "ModernGameController: 玩家死亡";

    // 停止游戏循环
    m_gameLoopTimer->stop();

    // 显示游戏结束
    emit gameEvent("player_died", m_currentScore);
}

void ModernGameController::onRoomCreated(const QString &roomId)
{
    qDebug() << "ModernGameController: 房间创建成功，房间ID:" << roomId;

    m_currentRoomId = roomId;

    // 作为创建者，自动开始游戏
    startGameInRoom();
}

void ModernGameController::onRoomJoined(const QString &roomId)
{
    qDebug() << "ModernGameController: 加入房间成功，房间ID:" << roomId;

    m_currentRoomId = roomId;

    // 等待房间创建者开始游戏
    qDebug() << "  等待游戏开始...";
}

void ModernGameController::startGameInRoom()
{
    qDebug() << "ModernGameController: 在房间中开始游戏，房间ID:" << m_currentRoomId;

    if (m_currentRoomId.isEmpty()) {
        qWarning() << "  房间ID为空，无法开始游戏";
        return;
    }

    if (!m_webSocketManager) {
        qWarning() << "  WebSocket管理器为空，无法开始游戏";
        return;
    }

    // 根据API文档发送开始游戏消息
    QJsonObject startGameMsg;
    startGameMsg["type"] = "start_game";
    startGameMsg["room_id"] = m_currentRoomId;

    // 发送开始游戏消息
    if (m_webSocketManager->sendMessage(startGameMsg)) {
        qDebug() << "  游戏开始请求已发送";
    } else {
        qWarning() << "  游戏开始请求发送失败";
    }
}

void ModernGameController::monitorThreadHealth()
{
    // 现在监控UnifiedGameRenderer的健康状态
    if (!m_unifiedRenderer || !m_unifiedRenderer->isRunning()) {
        return;
    }

    bool systemHealthy = true;

    // 检查UnifiedGameRenderer状态
    if (!m_unifiedRenderer->isRunning()) {
        qWarning() << "ModernGameController: UnifiedGameRenderer已停止";
        systemHealthy = false;
    }

    // 可以添加更多健康检查，比如FPS监控等
    int currentFPS = m_unifiedRenderer->currentFPS();
    if (currentFPS < 30 && currentFPS > 0) {  // FPS过低但不为0（0表示刚启动）
        qWarning() << "ModernGameController: FPS过低:" << currentFPS;
        // 不认为这是致命错误，只是警告
    }

    if (!systemHealthy) {
        m_threadFailureCount++;
        qWarning() << "ModernGameController: 系统健康检查失败，失败次数:" << m_threadFailureCount;

        if (m_threadFailureCount >= 3) {
            qWarning() << "ModernGameController: 系统失败次数过多，停止游戏";
            stopGame();
            m_threadMonitorTimer->stop();

            // 通知用户
            emit gameError("系统多次失败，游戏已停止");
        } else {
            // 尝试恢复系统
            attemptThreadRecovery();
        }
    } else {
        // 重置失败计数
        m_threadFailureCount = 0;
    }
}

void ModernGameController::attemptThreadRecovery()
{
    qDebug() << "ModernGameController: 尝试恢复失败的渲染器";

    // 重启UnifiedGameRenderer
    if (m_unifiedRenderer) {
        m_unifiedRenderer->stopGame();

        // 等待一段时间后重新启动
        QTimer::singleShot(1000, this, [this]() {
            qDebug() << "ModernGameController: 重新启动统一渲染器";

            UnifiedGameRenderer::RenderConfig config;
            config.targetFPS = 60;
            config.enableEffects = true;
            config.enableInterpolation = true;
            config.renderSize = QSize(800, 600);

            m_unifiedRenderer->startGame(GameMode::SinglePlayer, config);
        });
    }
}

void ModernGameController::sendDirectionToServer(int direction)
{
    if (!m_webSocketManager || !m_webSocketManager->isConnectedToGame()) {
        qDebug() << "ModernGameController: WebSocket未连接，无法发送方向控制";
        return;
    }

    // 根据API文档构建方向控制消息
    QJsonObject directionMsg;
    directionMsg["type"] = "change_direction";  // 修正：直接使用change_direction
    directionMsg["direction"] = direction;

    // 如果在房间中，添加房间ID
    if (!m_currentRoomId.isEmpty()) {
        directionMsg["room_id"] = m_currentRoomId;
        qDebug() << "ModernGameController: 发送方向控制到房间" << m_currentRoomId << "方向:" << direction;
    } else {
        qDebug() << "ModernGameController: 发送方向控制（无房间ID）方向:" << direction;
    }

    // 发送到服务器
    bool success = m_webSocketManager->sendMessage(directionMsg);
    if (!success) {
        qWarning() << "ModernGameController: 方向控制消息发送失败";
    } else {
        qDebug() << "ModernGameController: 方向控制消息发送成功";
    }
}

void ModernGameController::monitorMemoryUsage()
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

    // 每分钟检查一次内存使用
    if (currentTime - m_lastMemoryCheck < 60000) {
        return;
    }

    m_lastMemoryCheck = currentTime;

    // 简单的内存使用估算（基于游戏对象数量）
    qint64 estimatedMemoryKB = 0;

    // 估算游戏状态数据内存使用
    estimatedMemoryKB += m_currentFoods.size() * sizeof(QPoint) / 1024;

    // 估算渲染缓存内存使用
    if (m_gameRenderer) {
        // 假设每个缓存帧约1MB
        estimatedMemoryKB += 1024; // 1MB for cached frames
    }

    // 估算UnifiedGameRenderer内存使用
    if (m_unifiedRenderer) {
        estimatedMemoryKB += 200; // 估算渲染器内存使用
    }

    qint64 estimatedMemoryMB = estimatedMemoryKB / 1024;

    if (estimatedMemoryMB > MAX_MEMORY_MB) {
        qWarning() << "ModernGameController: 内存使用过高:" << estimatedMemoryMB << "MB，开始清理";
        cleanupMemoryCache();
    } else {
        qDebug() << "ModernGameController: 内存使用正常:" << estimatedMemoryMB << "MB";
    }
}

void ModernGameController::cleanupMemoryCache()
{
    qDebug() << "ModernGameController: 开始清理内存缓存";

    // 清理GameRenderer的缓存
    if (m_gameRenderer) {
        // 清空自定义帧缓存
        m_gameRenderer->setCustomFrame(QPixmap());
    }

    // 清理UnifiedGameRenderer的缓存
    if (m_unifiedRenderer) {
        // UnifiedGameRenderer内部会管理自己的缓存清理
        qDebug() << "  UnifiedGameRenderer缓存由内部管理";
    }

    // 强制垃圾回收（如果需要）
    // 注意：Qt没有显式的垃圾回收，但可以清理不必要的对象

    qDebug() << "ModernGameController: 内存缓存清理完成";
}

void ModernGameController::onRenderingError(const QString &error)
{
    qCritical() << "ModernGameController: 渲染错误:" << error;

    // 停止游戏
    if (m_unifiedRenderer) {
        m_unifiedRenderer->stopGame();
    }

    // 显示错误信息给用户
    // 这里可以添加错误对话框或状态显示

    // 尝试恢复到安全状态
    m_isGameRunning = false;
    m_currentGameState = "error";

    // 发送错误信号给主窗口
    emit gameError(error);
}